package cn.heroes.weixin.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.heroes.weixin.Utils;
import cn.heroes.weixin.app.spy.SpyService;
import cn.heroes.weixin.commons.XmlUtils;
import cn.heroes.weixin.pojo.Message;
import cn.heroes.weixin.services.IService;
import cn.heroes.weixin.type.MessageType;

public class MainServlet extends HttpServlet {

	private static final Logger logger = LoggerFactory
			.getLogger(MainServlet.class);
	private IService service = new SpyService();

//	@Override
//	public void init() throws ServletException {
//		super.init();
//		List<Object> menu = service.menu();
//		boolean success = Utils.createMenu(menu);
//		if (success)
//			logger.info("创建菜单成功");
//		else
//			logger.info("创建菜单失败");
//	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();

		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		boolean verify = Utils.verify(signature, timestamp, nonce);
		if (verify) {
			logger.info("首次对接验证成功.");
			out.print(echostr);
		} else {
			logger.info("首次对接验证失败.");
		}
		out.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();

		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");

		boolean verify = Utils.verify(signature, timestamp, nonce);

		if (verify) {
			logger.info("消息真实性验证成功.");
			ServletInputStream is = null;
			try {
				is = req.getInputStream();
				String xml = IOUtils.toString(is);
				Message msg = XmlUtils.toBean(xml, Message.class);
				if (MessageType.TEXT.equals(msg.msgType)) {
					service.text(msg);
				} else if (MessageType.EVENT.equals(msg.msgType)) {
					service.event(msg);
				} else if (MessageType.IMAGE.equals(msg.msgType)) {
				} else if (MessageType.LINK.equals(msg.msgType)) {
				} else if (MessageType.LOCATION.equals(msg.msgType)) {
				} else if (MessageType.VIDEO.equals(msg.msgType)) {
				} else if (MessageType.VOICE.equals(msg.msgType)) {
				}
			} catch (Exception e) {
				if (is != null)
					is.close();
			}
		} else {
			logger.warn("消息真实性验证失败.");
		}
	}
}
